package com.itheima.reggie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 *MetaObjectHandler这个接口可以在插入或更新数据时，自动填充一些默认值。
 * 原理就是往实体类里的对象设置值。
 * Component需要生成bean，让springboot加载其到ioc容器之中
 * 这个方法是在controller->service->MyMetaObjectHandler,所以这个方法是在最后才到的。
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入操作，自动填充
     * 插入时自动填充4个
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
      //  log.info("before");
       metaObject.setValue("createTable",LocalDateTime.now());
       metaObject.setValue("uptateTable",LocalDateTime.now());
        Employee principal = (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //BaseContext.getThreadLocal()获取到的只是ThreadLocal<Long>的对象，还需要通过get方法获取里面的Long对象
      /* metaObject.setValue("updateUser", BaseContext.getThreadLocal().get());
       metaObject.setValue("createUser",BaseContext.getThreadLocal().get());*/
        metaObject.setValue("updateUser",principal.getId());
        metaObject.setValue("createUser",principal.getId());
     // log.info("meta",BaseContext.getThreadLocal().get());
     // log.info("after");
    }
    /**
     *更新操作，自动填充*
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
         metaObject.setValue("uptateTable",LocalDateTime.now());
       //  metaObject.setValue("updateUser",BaseContext.getThreadLocal().get());
        Employee principal = (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
          metaObject.setValue("updateUser",principal.getId());
    }
}
